package com.example.demo.config;

import com.example.demo.service.SysSecurityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

/**
 * Copyright(C), 2020-2021, AmbroseCdMeng
 * FileName:    WebSecurityConfig
 * Author:      AmbroseCdMeng
 * Date:        2021/3/5 13:53
 * Description: 配置安全类
 * History:
 * <author>     <time>      <version>       <desc>
 * 作者姓名     修改时间        版本号           描述
 */
@Configuration
@EnableWebSecurity
@Order(1)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;

    @Bean
    /**
     * 使用 BCrypt 加密
     */
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/admin/**")
                // 指定登录认证的 Controller
                .formLogin()
                .usernameParameter("username")
                .passwordParameter("pwd")
                .loginPage("/admin/login")
                .successHandler(authenticationSuccessHandler)
                .failureHandler(authenticationFailureHandler)
                .and()
                .authorizeRequests()
                // 登录相关
                .antMatchers("/admin/login", "/admin/role", "/admin/user")
                .permitAll()
                // RABC 相关
                // 首次运行生成初始数据资料后取消注释
                //.antMatchers("/admin/rbac").access("@rbacService.hasPermission(request, authentication)")
                // 允许匿名访问，用于测试
                //.antMatchers("/admin/**").permitAll()
                .antMatchers("/admin/**").access("hasRole('ADMIN') or @rbacService.hasPermission(request, authentication)")
                // 加入权限验证，使权限功能启动
                .anyRequest().access("@rbacService.hasPermission(request, authentication)");
        http.logout().logoutUrl("/admin/logout").permitAll();
        // "记住我" 功能
        http.rememberMe().rememberMeParameter("rememberme");
        http.csrf().ignoringAntMatchers("/admin/upload");
        // 解决 X-Frame-Options deny 造成的页面空白，否则后台不能用 frame
        http.headers().frameOptions().sameOrigin();
    }

    @Bean
    UserDetailsService Service() {
        return new SysSecurityService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(Service()).passwordEncoder(new BCryptPasswordEncoder() {
        });
    }
}
